// 子账号列表
<template>
  <div class="app-container">
    <div style="margin-bottom:10px;">
      <el-button type="primary" @click="dialogFormVisible=!dialogFormVisible" size="small">新增子账号</el-button>
    </div>
    <div>
      <el-table :data="list" v-if="list" v-loading="loading" element-loading-text="加载中" size="small" header-cell-class-name='tableHeader' border stripe fit highlight-current-row>
        <el-table-column type="index" label="#" align="center" min-width="50"> </el-table-column>
        <el-table-column prop="" label="在线" align="center" min-width="50"> </el-table-column>
        <el-table-column prop="username" label="子账号" align="center" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="nickname" label="名称" align="center" min-width="80">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-input v-model="scope.row.nickname" size="small" placeholder="请输入名称" min="6" max="12" clearable></el-input>
            </template>
            <span v-else>{{ scope.row.nickname }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="user_auth_key" label="密码" align="center" min-width="80">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-input v-model="scope.row.user_auth_key" size="small" placeholder="请输入新密码" min="6" max="12" clearable></el-input>
            </template>
            <span v-else>******</span>
          </template>
        </el-table-column>

        <el-table-column prop="menus" label="功能权限" align="center" min-width="220">
          <template slot-scope="scope">
            <el-checkbox-group :disabled="!scope.row.edit" v-model="scope.row.menus">
              <el-checkbox v-for="(item,index) in userMap.menus" :key="`menus${item}`" :label="index">{{item}}</el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" align="center" min-width="150">
          <template slot-scope="scope">
            <template v-if="scope.row.edit">
              <el-radio-group :disabled="!scope.row.edit" v-model="scope.row.status" size="mini">
                <el-radio-button v-for="(item,index) in userMap.status" :key="`menus${item}`" :label="index">{{item}}</el-radio-button>
              </el-radio-group>
            </template>
            <template v-else>
              <span size="small">{{userMap.status[scope.row.status]}}</span>
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="created_date" label="新增日期" align="center" min-width="60"> </el-table-column>

        <el-table-column prop="" label="操作" align="center" min-width="150">
          <template slot-scope="scope">
            <el-button v-if="!scope.row.edit && !scope.row.delete" type="primary" @click='scope.row.edit=!scope.row.edit' size="small" icon="el-icon-edit">修改</el-button>
            <template v-if="scope.row.edit">
              <el-button type="success" @click="confirmEdit(scope.row)" size="small" icon="el-icon-circle-check-outline">保存</el-button>
              <el-button type="warning" @click="cancelEdit(scope.row)" size="small" icon="el-icon-circle-close-outline">取消</el-button>
            </template>
            <el-button v-if="!scope.row.edit && !scope.row.delete" type="danger" @click='scope.row.delete=!scope.row.delete' size="small" icon="el-icon-delete">删除</el-button>
            <template v-if="scope.row.delete">
              <el-button type="danger" @click="confirmDelete(scope.row)" size="small" icon="el-icon-delete">确认删除</el-button>
              <el-button type="warning" @click="scope.row.delete=!scope.row.delete" size="small" icon="el-icon-circle-close-outline">取消</el-button>
            </template>
          </template>
        </el-table-column>

      </el-table>
      <div class="pagination-container" v-if="pagination.totalCount > 0">
        <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10,20,30,50]" :page-size="params.perpage" :total="pagination.totalCount" layout="total,sizes,prev,pager,next,jumper" background>
        </el-pagination>
      </div>
    </div>

    <el-dialog title="新增子账号" :visible.sync="dialogFormVisible" width="40%" center>
      <el-form :rules="addFormRules" ref="addForm" :model="addForm" label-position="left" label-width="120px">
        <el-form-item prop="username" :label="(info.class)+`子账号`">
          <el-input type="text" placeholder="字母和数字组合" v-model="addForm.username" clearable></el-input>
        </el-form-item>

        <el-form-item prop="user_auth_key" label="登入密码">
          <el-input type="text" placeholder="6-10位字母或数字" v-model="addForm.user_auth_key" clearable></el-input>
        </el-form-item>

        <el-form-item prop="nickname" label="子账号名称`">
          <el-input type="text" placeholder="6-10位字母或数字" v-model="addForm.nickname" clearable></el-input>
        </el-form-item>

        <el-form-item prop="menus" label="各权限设定">
          <el-checkbox-group v-model="addForm.menus" @change="checkChange">
            <el-checkbox v-for="(item,index) in userMap.menus" :label="index" :key="`addAccountFormMenusCheckbox${index}`">{{item}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

      </el-form>

      <span slot="footer">
        <el-button type="primary" @click="confirmAdd">确定</el-button>
        <el-button @click="cancelAdd">取消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { user as userMap } from '@/utils/map' // 参数映射

export default {
  data() {
    return {
      dialogFormVisible: false, // 表单可见性
      addForm: {
        username: '',
        nickname: '',
        user_auth_key: '',
        reset_mode: 1, // 账号模式1:现金,2:信用
        menus: [],
      },
      addFormRules: {
        username: [
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            message: '请输入账号',
            transform(value) {
              return value.trim()
            },
          },
          {
            min: 5,
            message: '最少包含5个字符',
            trigger: 'change',
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            trigger: 'blur',
            message: '只能输入英文字符和数字',
          },
        ],
        nickname: [
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            message: '请输入名称',
            transform(value) {
              return value.trim()
            },
          },
          {
            min: 5,
            message: '最少包含5个字符',
            trigger: 'change',
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            trigger: 'blur',
            message: '只能输入英文字符和数字',
          },
        ],
        user_auth_key: [
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            message: '请输入密码',
          },
          {
            min: 6,
            message: '最少包含6个字符',
            trigger: 'change',
          },
          {
            pattern: /^[a-zA-Z0-9]+$/,
            trigger: 'blur',
            message: '只能输入英文字符和数字',
          },
        ],
        menus: [
          {
            required: true,
            trigger: 'change',
            message: '请选择权限',
          },
        ],
      },
      // 查詢參數
      params: {
        perpage: 2, // 每页数量
      },
      // 分页信息
      pagination: {
        currentPage: 1,
        totalCount: 0,
        defaultPageSize: 10,
      },
      list: null,
      loading: false,
      userMap: userMap,
    }
  },
  filters: {},
  computed: {
    ...mapGetters(['info']),
  },
  created() {
    // 拉取数据
    this.fetchData()
  },
  methods: {
    // 获取数据
    fetchData() {
      this.loading = true
      this.$store
        .dispatch('ListSubAccount', {
          params: this.params, // 分页参数
          pagination: this.pagination,
        })
        .then(response => {
          this.loading = false
          console.log('++++++++++++', response)
          const res = response.list
          // 遍历格式化数据
          this.list = res.map(row => {
            this.$set(row, 'edit', false) // 需要绑定的属性要先声明
            this.$set(row, 'delete', false) // 需要绑定的属性要先声明
            row.menus = row.menus.split(',') // 转化成arr

            row.initNickname = row.nickname //  不用绑定的属性
            row.initMenus = row.menus //  不用绑定的属性
            row.initStatus = row.status //  不用绑定的属性
            row.user_auth_key = '' //  不用绑定的属性

            return row
          })

          this.pagination.totalCount = parseInt(response.pagination.totalCount)

          this.pagination.defaultPageSize = parseInt(
            response.pagination.defaultPageSize
          )
        })
    },
    checkChange(...args) {
      // console.log(args);
    },
    // 添加确认
    confirmAdd() {
      // 验证数据
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 新增子账号
          this.$store
            .dispatch('ValidateAddSubAccount', { SubAccountForm: this.addForm })
            .then(response => {
              this.loading = false
              this.errorMsg = ''
              console.log('response.length === 0', response.status)
              if (response.status) {
                this.loading = true
                // 服务端验证通过
                this.$store
                  .dispatch('AddSubAccount', { SubAccountForm: this.addForm })
                  .then(res => {
                    this.loading = false
                    console.log('************', res)
                    if (parseInt(res)) {
                      // 添加成功,返回id
                      this.dialogFormVisible = false // 隐藏dialog
                      this.$message({
                        message: '新增成功!',
                        type: 'success',
                      })
                      //
                      this.fetchData()
                    } else {
                      this.$message({
                        message: Object.values(res)[0].toString(),
                        type: 'error',
                      })
                    }
                  })
                  .catch(error => {
                    console.log(error)
                    this.loading = false
                  })
              } else {
                // 验证失败
                this.$message({
                  message: Object.values(response)[0].toString(),
                  type: 'error',
                })
                console.log('服务器端验证失败')
              }
            })
            .catch(error => {
              console.log(error)
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 取消添加
    cancelAdd() {
      this.dialogFormVisible = false
      this.$refs.addForm.resetFields()
    },

    // 取消修改
    cancelEdit(row) {
      row.edit = false
      row.nickname = row.initNickname
      row.menus = row.initMenus
      row.status = row.initStatus
      row.user_auth_key = ''
    },

    // 更新子账号
    confirmEdit(row) {
      // 验证数据
      if (row.username.trim().length <= 0) {
        this.$message({
          message: '请填写账号',
          type: 'error',
        })
        return
      } else if (row.nickname.trim().length <= 0) {
        this.$message({
          message: '请填写名称',
          type: 'error',
        })
        return
      }
      if (row.user_auth_key.trim().length <= 0) {
        row.user_auth_key = ''
      }

      this.loading = true
      // 修改
      this.$store
        .dispatch('ValidateUpdateSubAccount', { SubAccountUpdateForm: row })
        .then(response => {
          this.loading = false
          this.errorMsg = ''
          if (response.length === 0) {
            this.loading = true
            // 服务端验证通过
            this.$store
              .dispatch('UpdateSubAccount', { SubAccountUpdateForm: row })
              .then(res => {
                this.loading = false
                if (res === true) {
                  // 编辑成功
                  row.edit = false // 隐藏编辑栏
                  this.$message({
                    message: '修改成功!',
                    type: 'success',
                  })
                  this.fetchData()
                } else {
                  this.$message({
                    message: Object.values(res)[0].toString(),
                    type: 'error',
                  })
                }
              })
              .catch(error => {
                console.log(error)
                this.loading = false
              })
          } else {
            // 验证失败
            this.$message({
              message: Object.values(response)[0].toString(),
              type: 'error',
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.loading = false
        })
    },

    // 确认删除
    confirmDelete(row) {
      row.delete = false
      this.$store
        .dispatch('DeleteSubAccount', { username: row.username })
        .then(response => {
          this.loading = false
          // console.log(response);
          if (response === true) {
            this.$message({
              message: '删除成功',
              type: 'success',
            })
            this.fetchData()
          } else {
            // 验证失败
            this.$message({
              message: Object.values(response)[0].toString(),
              type: 'error',
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.loading = false
        })
    },

    // 当前页变化
    handleCurrentChange(value) {
      this.pagination.currentPage = value
      this.fetchData()
    },

    // 每页显示数量变化
    handlePageSizeChange(value) {
      this.params.perpage = value
      this.fetchData()
    },
  },
  watch: {
    $route(to, from) {
      // 监控路由变化,从新加载数据
      if (to.params !== from.params) {
        console.log(to.params)
      }
    },
  },
}
</script>
<style>
.table-container {
}
.pagination-container {
  padding: 10px 0 0 30px;
}
</style>

